package com.hup.utils.algorithm.image;

import lombok.extern.log4j.Log4j2;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.image.MemoryImageSource;
import java.awt.image.PixelGrabber;

/**
 * 将rgb图像转成灰度图,且保留透明像素(不被转成黑色)
 * <pre>
 * 单纯的 new BufferedImage() {@link BufferedImage#TYPE_BYTE_GRAY}会使透明像素变成黑色
 * RGB转灰度算法
 *  https://blog.csdn.net/u012308586/article/details/94619769
 * </pre>
 *
 * @author hugan
 * @date 2020/6/1
 */
@Log4j2
public class GrayWithAlpha {

    public static Image toGray(Image image) throws InterruptedException {
        int imageWidth = image.getWidth(null);
        int imageHeight = image.getHeight(null);
        PixelGrabber pgr = new PixelGrabber(image, 0, 0, -1, -1, true);
        pgr.grabPixels();

        int argbs[] = (int[]) pgr.getPixels();
        log.debug("argbs={}", argbs.length);
        for (int i = argbs.length - 1; i >= 0; i--) {
            int a = (argbs[i] >> 24) & 0xff;
            int r = (argbs[i] >> 16) & 0xff;
            int g = (argbs[i] >> 8) & 0xff;
            int b = (argbs[i]) & 0xff;
            if (a != 0) {
                int gray = (int) ((r * 299 + g * 587 + b * 114) / 1000f);
                argbs[i] = getColor(255, gray, gray, gray);
            }
        }
        return Toolkit.getDefaultToolkit().createImage(new MemoryImageSource(imageWidth, imageHeight, argbs, 0, imageWidth));
    }

    private static int getColor(int a, int r, int g, int b) {
        return ((a & 0xFF) << 24) | ((r & 0xFF) << 16) | ((g & 0xFF) << 8) | ((b & 0xFF));
    }

}
